﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Web;
using ADC.Comet.Core;
using Newtonsoft.Json;
using Sharp.Framework.Extensions;

namespace Sharp.Framework.Comet
{
    /// <summary>
    /// 异步请求类
    /// </summary>
    public class AsyncRequest : IAsyncResult
    {
        /// <summary>
        /// 请求用户id
        /// </summary>
        public readonly int UserId; 
  


        /// <summary>
        /// 请求创建时间
        /// </summary>
        public readonly long Created;

        private readonly AsyncCallback _asyncCallback;
        private readonly object _data;
        private bool _isCompleted;

        public AsyncRequest(AsyncCallback callback, Object extraData, int userId)
        {
            _data = extraData;
            UserId = userId;
            _asyncCallback = callback;
            _isCompleted = false;
            Created = DateTime.Now.GenerateTimeStamp();
        }

        readonly StringBuilder _cache = new StringBuilder();

        public void Write(List<Message> content, long last)
        {
            
            var contentXml = JsonConvert.SerializeObject(new AsyncMessageResult(last, content)); 
           _cache.Append(contentXml);
        }

        public void Send(HttpContext context)
        {
            context.Response.Write(_cache.ToString());
        }

        public void Complete(object data)
        {
            try
            {

                _asyncCallback(this);
                _isCompleted = true;
            }
            catch
            {

            }
        }


        bool IAsyncResult.IsCompleted { get { return _isCompleted; } }

        bool IAsyncResult.CompletedSynchronously { get { return false; } }

        WaitHandle IAsyncResult.AsyncWaitHandle { get { return null; } }

        Object IAsyncResult.AsyncState { get { return _data; } }
    }
}